/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * Clientes.java
 *
 * Created on 04-dic-2011, 19:41:39
 */
package formularios;

import clases.ConversorRSaDefaultTableModel;
import clases.abmCliente;
import clases.conexion;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author Ele
 */
public class Clientes extends javax.swing.JDialog {

    /** Creates new form Clientes */
    public Clientes(java.awt.Frame parent, boolean modal) {
        
        super(parent, modal);
        initComponents();
        completartablaClientes();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPopupMenu1 = new javax.swing.JPopupMenu();
        Editar = new javax.swing.JMenuItem();
        Eliminar = new javax.swing.JMenuItem();
        jLayeredPane1 = new javax.swing.JLayeredPane();
        NuevoCliente = new javax.swing.JInternalFrame();
        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();
        jPanel2 = new javax.swing.JPanel();
        ftfCUIT = new javax.swing.JFormattedTextField();
        tfRazonSocial = new javax.swing.JTextField();
        tfDomicilio = new javax.swing.JTextField();
        tfTelefono = new javax.swing.JTextField();
        btnAgregar = new javax.swing.JButton();
        jLabel3 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        btnNuevoCliente = new javax.swing.JButton();
        t = new javax.swing.JScrollPane();
        tablaClientes = new javax.swing.JTable();
        tfBuscaCliente = new javax.swing.JTextField();
        jLabel7 = new javax.swing.JLabel();

        Editar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/iconos/lapiz.png"))); // NOI18N
        Editar.setText("Editar");
        Editar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                EditarActionPerformed(evt);
            }
        });
        jPopupMenu1.add(Editar);

        Eliminar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/iconos/Symbol-Restricted.png"))); // NOI18N
        Eliminar.setText("Eliminar");
        Eliminar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                EliminarActionPerformed(evt);
            }
        });
        jPopupMenu1.add(Eliminar);

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Modulo Clientes");
        setResizable(false);

        NuevoCliente.setClosable(true);
        NuevoCliente.setTitle("Nuevo cliente");
        NuevoCliente.setFrameIcon(new javax.swing.ImageIcon(getClass().getResource("/iconos/roles.png"))); // NOI18N
        NuevoCliente.addInternalFrameListener(new javax.swing.event.InternalFrameListener() {
            public void internalFrameActivated(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameClosed(javax.swing.event.InternalFrameEvent evt) {
                NuevoClienteInternalFrameClosed(evt);
            }
            public void internalFrameClosing(javax.swing.event.InternalFrameEvent evt) {
                NuevoClienteInternalFrameClosing(evt);
            }
            public void internalFrameDeactivated(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameDeiconified(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameIconified(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameOpened(javax.swing.event.InternalFrameEvent evt) {
            }
        });

        jPanel1.setLayout(new java.awt.GridLayout(4, 0, 5, 5));

        jLabel1.setText("CUIT/CUIL");
        jPanel1.add(jLabel1);

        jLabel4.setText("Razon Social");
        jPanel1.add(jLabel4);

        jLabel5.setText("Domicilio");
        jPanel1.add(jLabel5);

        jLabel6.setText("Telefono");
        jPanel1.add(jLabel6);

        jPanel2.setLayout(new java.awt.GridLayout(4, 0, 5, 5));

        try {
            ftfCUIT.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("##-########-#")));
        } catch (java.text.ParseException ex) {
            ex.printStackTrace();
        }
        ftfCUIT.setToolTipText("Ingresarel CUIT del Cliente");
        jPanel2.add(ftfCUIT);

        tfRazonSocial.setToolTipText("Ingresar la razon social");
        jPanel2.add(tfRazonSocial);

        tfDomicilio.setToolTipText("Ingresar el domicilio");
        jPanel2.add(tfDomicilio);

        tfTelefono.setToolTipText("ingresar Telefono");
        jPanel2.add(tfTelefono);

        btnAgregar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/iconos/Symbol-Add.png"))); // NOI18N
        btnAgregar.setText("Agregar");
        btnAgregar.setToolTipText("Hacer click para agregar el Cliente a la Base de Datos");
        btnAgregar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAgregarActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout NuevoClienteLayout = new javax.swing.GroupLayout(NuevoCliente.getContentPane());
        NuevoCliente.getContentPane().setLayout(NuevoClienteLayout);
        NuevoClienteLayout.setHorizontalGroup(
            NuevoClienteLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, NuevoClienteLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(NuevoClienteLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(btnAgregar, javax.swing.GroupLayout.PREFERRED_SIZE, 209, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(NuevoClienteLayout.createSequentialGroup()
                        .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, 116, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, 292, Short.MAX_VALUE)))
                .addContainerGap())
        );
        NuevoClienteLayout.setVerticalGroup(
            NuevoClienteLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(NuevoClienteLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(NuevoClienteLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                    .addComponent(jPanel2, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jPanel1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 136, Short.MAX_VALUE))
                .addGap(31, 31, 31)
                .addComponent(btnAgregar, javax.swing.GroupLayout.PREFERRED_SIZE, 34, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(29, Short.MAX_VALUE))
        );

        NuevoCliente.setBounds(40, 30, 450, 270);
        jLayeredPane1.add(NuevoCliente, javax.swing.JLayeredPane.DEFAULT_LAYER);

        jLabel3.setFont(new java.awt.Font("Times New Roman", 1, 18));
        jLabel3.setText("Clientes");
        jLabel3.setBounds(220, 10, 62, 22);
        jLayeredPane1.add(jLabel3, javax.swing.JLayeredPane.DEFAULT_LAYER);

        jLabel2.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
        jLabel2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/iconos/buca.png"))); // NOI18N
        jLabel2.setText("Buscar Cliente por Razon Social");
        jLabel2.setBounds(290, 280, 230, 23);
        jLayeredPane1.add(jLabel2, javax.swing.JLayeredPane.DEFAULT_LAYER);

        btnNuevoCliente.setIcon(new javax.swing.ImageIcon(getClass().getResource("/iconos/roles.png"))); // NOI18N
        btnNuevoCliente.setText("Nuevo Cliente");
        btnNuevoCliente.setToolTipText("Haga click para agregar un nuevo cliente");
        btnNuevoCliente.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnNuevoClienteActionPerformed(evt);
            }
        });
        btnNuevoCliente.setBounds(10, 300, 160, 40);
        jLayeredPane1.add(btnNuevoCliente, javax.swing.JLayeredPane.DEFAULT_LAYER);

        tablaClientes.setAutoCreateRowSorter(true);
        tablaClientes.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, false, false, false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        tablaClientes.setToolTipText("Haga click derecho sobre el CUIT/CUIL  para editar o eliminar un cliente");
        tablaClientes.setComponentPopupMenu(jPopupMenu1);
        tablaClientes.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
        tablaClientes.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                tablaClientesMouseClicked(evt);
            }
        });
        t.setViewportView(tablaClientes);
        tablaClientes.getColumnModel().getColumn(0).setResizable(false);
        tablaClientes.getColumnModel().getColumn(1).setResizable(false);
        tablaClientes.getColumnModel().getColumn(2).setResizable(false);
        tablaClientes.getColumnModel().getColumn(3).setResizable(false);

        t.setBounds(10, 40, 520, 230);
        jLayeredPane1.add(t, javax.swing.JLayeredPane.DEFAULT_LAYER);

        tfBuscaCliente.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                tfBuscaClienteKeyReleased(evt);
            }
        });
        tfBuscaCliente.setBounds(270, 310, 220, 30);
        jLayeredPane1.add(tfBuscaCliente, javax.swing.JLayeredPane.DEFAULT_LAYER);

        jLabel7.setForeground(new java.awt.Color(0, 51, 204));
        jLabel7.setText("Limpiar busqueda");
        jLabel7.setToolTipText("Hacer click para limpiar el campo de busqueda");
        jLabel7.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
        jLabel7.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jLabel7MouseClicked(evt);
            }
        });
        jLabel7.setBounds(330, 340, 110, 20);
        jLayeredPane1.add(jLabel7, javax.swing.JLayeredPane.DEFAULT_LAYER);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLayeredPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 539, Short.MAX_VALUE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLayeredPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 365, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(21, Short.MAX_VALUE))
        );

        java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
        setBounds((screenSize.width-575)/2, (screenSize.height-435)/2, 575, 435);
    }// </editor-fold>//GEN-END:initComponents

    private void btnAgregarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAgregarActionPerformed

        String CUIT = ftfCUIT.getText();
        String razonsocial = tfRazonSocial.getText();
        String domicilio = tfDomicilio.getText();
        String telefono = tfTelefono.getText();



        if (modificar == false) {


            if (CUIT.equals("  -        - ")) {
                JOptionPane.showMessageDialog(null, "Por favor ingrese el CUIT", "Error", JOptionPane.ERROR_MESSAGE);
            } else {
                if (!new abmCliente().ExisteCliente(CUIT)) {
                    new abmCliente().AltaCliente(CUIT, razonsocial, domicilio, telefono);
                    limpiar();
                    NuevoCliente.setVisible(false);
                    btnNuevoCliente.setEnabled(true);
                    completartablaClientes();


                } else {
                    JOptionPane.showMessageDialog(null, "EL CUIT ingresado ya esta registrado", "Error", JOptionPane.ERROR_MESSAGE);
                    limpiar();
                }
            }
        }
         else {
            if (CUIT.equals("  -        - ")) {
                JOptionPane.showMessageDialog(null, "Por favor ingrese el CUIT", "Error", JOptionPane.ERROR_MESSAGE);
            }
        
    

    
        else{
          
                new abmCliente().ModificaCliente(cliente, CUIT, razonsocial, domicilio, telefono);
        completartablaClientes();
        limpiar();
        NuevoCliente.setVisible(false);
        btnNuevoCliente.setEnabled(true);
    }

        }   
    }//GEN-LAST:event_btnAgregarActionPerformed

    
  public void completarDatos(String CUIT){
        String datos[] = new String [3];
        datos= new abmCliente().BuscaClienteCUIT(CUIT);
                tfRazonSocial.setText(datos[0]);
                ftfCUIT.setText(CUIT);
                tfDomicilio.setText(datos[1]);
                tfTelefono.setText(datos[2]);
                
            
            
        
    }
    
    
    private void btnNuevoClienteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnNuevoClienteActionPerformed
        modificar=false;
        NuevoCliente.setVisible(true);
         btnNuevoCliente.setEnabled(false);
         NuevoCliente.setTitle("Nuevo cliente");
         btnAgregar.setText("Agregar");
         btnAgregar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/iconos/Symbol-Add.png"))); // NOI18N
         btnAgregar.setToolTipText("Hacer click para agregar el Cliente a la Base de Datos");
         
    }//GEN-LAST:event_btnNuevoClienteActionPerformed

    private void tfBuscaClienteKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_tfBuscaClienteKeyReleased
   String buscar = tfBuscaCliente.getText();
  
  ResultSet buscando = new abmCliente().BuscarCliente(buscar);
   tablaClientes.setAutoResizeMode(tablaClientes.AUTO_RESIZE_ALL_COLUMNS);
              
   ConversorRSaDefaultTableModel.completar(buscando, modelo);
    }//GEN-LAST:event_tfBuscaClienteKeyReleased

    private void jLabel7MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLabel7MouseClicked
         tfBuscaCliente.setText("");
         completartablaClientes();
    }//GEN-LAST:event_jLabel7MouseClicked

    private void NuevoClienteInternalFrameClosed(javax.swing.event.InternalFrameEvent evt) {//GEN-FIRST:event_NuevoClienteInternalFrameClosed
     btnNuevoCliente.setEnabled(true);
     limpiar();
    }//GEN-LAST:event_NuevoClienteInternalFrameClosed

    private void NuevoClienteInternalFrameClosing(javax.swing.event.InternalFrameEvent evt) {//GEN-FIRST:event_NuevoClienteInternalFrameClosing
    btnNuevoCliente.setEnabled(true);
    limpiar();
    }//GEN-LAST:event_NuevoClienteInternalFrameClosing

    private void EditarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_EditarActionPerformed
      modificar=true;
        NuevoCliente.setVisible(true);
      btnAgregar.setText("Guardar Cambios");
      NuevoCliente.setTitle("Modificar cliente");
      btnAgregar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/iconos/lapiz.png"))); // NOI18N
      completarDatos(cliente);
      btnNuevoCliente.setEnabled(false);
      btnAgregar.setToolTipText("Hacer click para guardar los cambios a la Base de Datos");
      
    }//GEN-LAST:event_EditarActionPerformed

    private void tablaClientesMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tablaClientesMouseClicked
        int fila = tablaClientes.rowAtPoint(evt.getPoint()); 

         int columna = tablaClientes.columnAtPoint(evt.getPoint());
         if ((fila > -1) && (columna == 1)){
         cliente = String.valueOf(modelo.getValueAt(fila,columna)); 
         System.out.println(cliente);
         }
        
   
    }//GEN-LAST:event_tablaClientesMouseClicked

    private void EliminarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_EliminarActionPerformed
        if (cliente == null){
            JOptionPane.showMessageDialog(null,"El cliente debe poseer un numero de CUIT","Error",JOptionPane.ERROR_MESSAGE);
        }
        else{
        new abmCliente().BajaCliente(cliente);
        
        }
        completartablaClientes();
    }//GEN-LAST:event_EliminarActionPerformed

    public void Conectar(){
        try{
            mdbc = new conexion();
            mdbc.init();
            Connection conn= mdbc.getMyConnection();
            stmt = conn.createStatement();
        }catch(Exception ex)
        {
            JOptionPane.showMessageDialog(null, "Problemas al concetarse a la Base de Datos","Error",JOptionPane.ERROR_MESSAGE);
        }
    }   
    
    private void completartablaClientes() {
        String sql = "Select razonsocial as 'Cliente',  cuit as 'CUIT', domicilio as 'Domicilio', telefono as 'Telefono'"
                + "     from Cliente";
                
        try {
            Conectar();
            ResultSet rs = stmt.executeQuery(sql);

      
            tablaClientes.setModel(modelo);
            tablaClientes.setAutoResizeMode(tablaClientes.AUTO_RESIZE_ALL_COLUMNS);
              
                    
            ConversorRSaDefaultTableModel.completar(rs, modelo);

        } catch (Exception ex) {
            JOptionPane.showMessageDialog(null, "Error en la consulta de animales", "Error", JOptionPane.ERROR_MESSAGE);
        }
        
    }
    
    
    public void limpiar(){
        ftfCUIT.setText("");
        tfRazonSocial.setText("");
        tfDomicilio.setText("");
        tfTelefono.setText("");
    }
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(Clientes.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Clientes.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Clientes.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Clientes.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the dialog */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                Clientes dialog = new Clientes(new javax.swing.JFrame(), true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {

                    @Override
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }
    
    
      private conexion mdbc;
  private Statement stmt;
   DefaultTableModel modelo = new DefaultTableModel();
   String cliente;
   boolean modificar=false;
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JMenuItem Editar;
    private javax.swing.JMenuItem Eliminar;
    private javax.swing.JInternalFrame NuevoCliente;
    private javax.swing.JButton btnAgregar;
    private javax.swing.JButton btnNuevoCliente;
    private javax.swing.JFormattedTextField ftfCUIT;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLayeredPane jLayeredPane1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPopupMenu jPopupMenu1;
    private javax.swing.JScrollPane t;
    private javax.swing.JTable tablaClientes;
    private javax.swing.JTextField tfBuscaCliente;
    private javax.swing.JTextField tfDomicilio;
    private javax.swing.JTextField tfRazonSocial;
    private javax.swing.JTextField tfTelefono;
    // End of variables declaration//GEN-END:variables
}
